package com.cn.web.servlet;

import com.alibaba.fastjson.JSON;
import com.cn.pojo.Brand;
import com.cn.service.BrandService;
import com.cn.service.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrandService brandService = new BrandServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Enter selectAllServlet");
        //1.调用Service查询
        List<Brand> brands = brandService.selectAll();
        //2.JSON
        String jsonString = JSON.toJSONString(brands);
        //3.写数据
        //告知浏览器响应的数据是什么， 告知浏览器使用什么字符集进行解码
        resp.setContentType("text/json;charset=utf-8");
        //通过 HttpServletResponse 的 getWriter() 方法，
        // 获取输出流并将 JSON 字符串写入到响应中，发送给客户端。
        //resp.setHeader("content-type", "text/json;charset=utf-8");
        //这两个是相等的，但是建议使用setContentType

        //网页上确实会打印出来
        resp.getWriter().write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
